﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KP_CommonLibrary.KP_CoreUI;
using KP_CommonLibrary.KP_Interface;
using KEEPER_BRR_13dotNET.BusinessLogic;
using KP_CommonLibrary;
using KP_CommonLibrary.Logs;
using KP_CommonLibrary.KP_CommonControls;
using System.Diagnostics;
using DevComponents.DotNetBar.SuperGrid;
using EnvDTE;
using DevComponents.DotNetBar;
using KP_CommonLibrary.KP_Business;

namespace KEEPER_BRR_13dotNET.Presentation
{

    public partial class FrmE_HoSoMoi : KP_CommonLibrary.KP_CoreUI.KP_EditListItem, IRunCommand
    {
        BL_KPHoSo _CastBussines;
        public string MaLoaiHoSo { get; set; }
        DataTable tblCacheGiayToKemTheo = null;
        DataTable tblGiayToHienTai = null;

        public FrmE_HoSoMoi()
        {
            InitializeComponent();
            if (!DesignMode)
            {
                tblCacheGiayToKemTheo = new DataTable("GiayToKemTheo");
                MaLoaiHoSo = "DK";
                _CastBussines = new BL_KPHoSo();
                GridCheckBoxXEditControl ckChoice = (GrdCtNganh.PrimaryGrid.Columns["Choice"].EditControl as GridCheckBoxXEditControl);
                ckChoice.CheckedChangedEx += new DevComponents.DotNetBar.Controls.CheckBoxXChangeEventHandler(ckChoice_CheckedChangedEx);
                GrdCtNganh.PrimaryGrid.GroupColumns.Add(GrdCtNganh.PrimaryGrid.Columns["Ten_Nhom"]);

                GridComboBoxExEditControl cb = null;
                DataTable tblData = null;
                cb = (GridComboBoxExEditControl)GrdCtGiayto.PrimaryGrid.Columns["Ma_TcGt"].EditControl;
                if (cb.DataSource == null)
                {
                    cb.DisplayMember = "Ten_TcGt";
                    cb.ValueMember = "Ma_TcGt";
                    tblData = tblData ?? BL_KPDictionary.GetDmTcGtTable();
                    cb.DataSource = new DataView(tblData);
                }
                cb = (GridComboBoxExEditControl)GrdCtGiayto.PrimaryGrid.Columns["Ma_TcGt"].RenderControl;
                if (cb.DataSource == null)
                {
                    cb.DisplayMember = "Ten_TcGt";
                    cb.ValueMember = "Ma_TcGt";
                    tblData = tblData ?? BL_KPDictionary.GetDmTcGtTable();
                    cb.DataSource = new DataView(tblData);
                }
            }
        }



        public override void InitData(DataRow row)
        {
            row["Stt_Rec"] = BL_KPCommon.EmptySttRec;
            row["Ma_LoaiHs"] = MaLoaiHoSo;
            row["Ngay_Nop"] = DateTime.Now.Date;
            row["Ngay_Hen"] = DateTime.Now.AddDays(4).Date;
            row["So_Bn"] = "[Tự sinh]";
            row["Ma_Hs"] = 0;
            row["Ma_Tt"] = CauHinh.TrangThaiHsMacDinh();
            base.InitData(row);
        }
        public override void LoadDependencyData()
        {
            try
            {

                BL_KPDmLoaiHs blLoaiHs = new BL_KPDmLoaiHs();
                BL_KPDmTt blTrangThai = new BL_KPDmTt();
                BL_KPDmPx blPx = new BL_KPDmPx();
                if (cbGioi_Tinh.DataSource == null)
                {
                    DataTable tblGioiTinh = new DataTable("GioiTinh");
                    tblGioiTinh.Columns.Add("ID");
                    tblGioiTinh.Columns.Add("Name");
                    tblGioiTinh.Rows.Add("Nam", "Nam");
                    tblGioiTinh.Rows.Add("Nu", "Nữ");
                    tblGioiTinh.Rows.Add("Khac", "Khác");
                    cbGioi_Tinh.DisplayMember = "Name";
                    cbGioi_Tinh.ValueMember = "ID";

                    cbGioi_Tinh.DataSource = tblGioiTinh;
                }
                //Load danh muc loai ho so
                if (cbLoaiHs.DataSource == null)
                {
                    cbLoaiHs.DisplayMember = "Ten_LoaiHs";
                    cbLoaiHs.ValueMember = "Ma_LoaiHs";
                    cbLoaiHs.DataSource = blLoaiHs.Select();
                }
                //Loa danh mục trạng thái
                if (cbTrangThai.DataSource == null)
                {
                    cbTrangThai.DisplayMember = "Ten_Tt";
                    cbTrangThai.ValueMember = "Ma_Tt";
                    cbTrangThai.DataSource = blTrangThai.Select();
                }
                //Danh mục phường xã
                if (cboMa_Px.DataSource == null)
                    cboMa_Px.DataSource = blPx.SelectByMaHuyen("02");

                //Schema tblThanhVienHSo
                LoadThanhVienSchema();
                bsThanhVien.DataSource = dsDKHoSoKD.Tables["tblThanhVienHSo"];
                LoadTpHoSoSchema();
                //Lấy thông tin ngành nghề





                base.LoadDependencyData();
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Fatal("Lấy dữ liệu liên quan", ex);
                KPMessageBox.Show("Lấy dữ liệu liên quan\n" + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);

            }

        }


        protected override void CreateBusiness()
        {
            Business = _CastBussines;
        }
        public override void AddNew(CurrencyManager cm)
        {
            try
            {
                if (cm == null)
                {
                    InitDatasource();
                }
                else
                    ParentBinding = cm;

                ParentBinding.AddNew();
                LoadTpHoSoSchema();
                InitData((ParentBinding.Current as DataRowView).Row);
                LoadDependencyData();
                LoadNganhHs(BL_KPCommon.EmptySttRec);
                LoadTpHoSoMacDinh(true);
                SetDataSource(ParentBinding.Current);
                FormState = FormState.Insert;
            }
            catch (Exception ex)
            {
                try
                {
                    if ((ParentBinding.Current as DataRowView).Row.RowState == DataRowState.Detached)
                        (ParentBinding.Current as DataRowView).Row.Delete();
                    else
                        ParentBinding.CancelCurrentEdit();
                }
                catch
                {
                }
                throw ex;
            }
        }
        public override void Edit(CurrencyManager cm)
        {

        }
        protected override void EndEdit()
        {
            GrdDsTV.PrimaryGrid.FlushActiveRow();
            GrdCtNganh.PrimaryGrid.FlushActiveRow();
            GrdCtGiayto.PrimaryGrid.FlushActiveRow();
            bsNganhKD.EndEdit();
            bsCtTpHoSo.EndEdit();
            bsHoSoCaNhan.EndEdit();
            base.EndEdit();
        }
        protected override void Save(bool saveAndNew)
        {
            string state = "";
            try
            {
                state = "Kết thúc cập nhật\n";
                EndEdit();
                state = "Kiểm tra dữ liệu\n";
                if (ValidateAll())
                {
                    state = "Lưu thông tin\n";
                    if (FormState == FormState.Insert)
                    {


                        _CastBussines.Insert(CurrentRow,
                                                bsThanhVien.DataSource as DataTable,
                                                bsNganhKD.DataSource as DataTable,
                                                bsCtTpHoSo.DataSource as DataTable);
                        // Business.Insert(CurrentRow,bs);
                    }
                    else
                    {
                        _CastBussines.Update(CurrentRow,
                                                bsThanhVien.DataSource as DataTable,
                                                bsNganhKD.DataSource as DataTable,
                                                bsCtTpHoSo.DataSource as DataTable);
                    }
                    CurrentRow.AcceptChanges();
                    FormState = FormState.Unspecified;

                    if (saveAndNew)
                    {
                        state = "Khởi tạo bản ghi mới\n";
                        AddNew(ParentBinding);
                    }
                    else
                        Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(state + ex.Message);
            }
        }
        public override bool ValidateAll()
        {

            bool flag = base.ValidateAll();
            if (flag)
            {
                DataView view1 = grdNganhDaChon.PrimaryGrid.DataSource as DataView;
                if (view1.Count == 0 && string.IsNullOrEmpty(txtNganhNgheKhac.Text))
                {
                    KPMessageBox.Show("Bạn chưa chọn ngành nghề kinh doanh", KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Warning);
                    return false;
                }
                DataTable tblData = bsCtTpHoSo.DataSource as DataTable;
                DataRow[] unChecks = tblData.Select("Co=0 AND Bat_Buoc=1");
                if (unChecks.Length > 0)
                {
                    string message = "Các giấy tờ sau bắt buộc phải có trong hồ sơ:\n";
                    foreach (DataRow row in unChecks)
                        message += "\t+" + row["Ten_LoaiGt"] + "\n";
                    KPMessageBox.Show(message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Warning);
                    return false;
                }

            }
            return flag;
        }

        void LoadThanhVien(string sttRec)
        {
            dsDKHoSoKD.Merge(_CastBussines.SelectThanhVienBySttRec(sttRec));
            bsThanhVien.DataSource = dsDKHoSoKD.Tables["tblThanhVienHSo"];
        }
        void LoadNganhHs(string sttRec)
        {
            if (bsNganhKD.DataSource != null)
            {
                dsDKHoSoKD.Tables["tblNganhHSo"].Clear();
            }
            dsDKHoSoKD.Merge(_CastBussines.SelectNganhHSBySttRec(sttRec));
            dsDKHoSoKD.Tables["tblNganhHSo"].ColumnChanged += new DataColumnChangeEventHandler(FrmE_HoSoMoi_ColumnChanged);
            bsNganhKD.DataSource = dsDKHoSoKD.Tables["tblNganhHSo"];
            DataView selectedView = new DataView(dsDKHoSoKD.Tables["tblNganhHSo"]);
            selectedView.RowFilter = "Choice=1";
            grdNganhDaChon.PrimaryGrid.DataSource = selectedView;
        }
        void LoadTpHoSoMacDinh(bool addToList)
        {
            //Lấy danh sách giấy tờ theo loại hồ sơ
            DataView view = new DataView(tblCacheGiayToKemTheo);
            view.RowFilter = "Ma_DoiTuong='" + MaLoaiHoSo + "' AND Loai_DoiTuong=1";
            DataTable tblGiayTo = view.ToTable();
            tblGiayToHienTai = tblGiayTo.Copy();
            LoadTpHoSoSchema();
            if (!addToList) return;

            DataTable tblTpHoSo = dsDKHoSoKD.Tables["tblTpHoSo"];
            foreach (DataRow row in tblGiayTo.Rows)
                AddGiayTo(tblTpHoSo, row);
            bsCtTpHoSo.DataSource = tblTpHoSo;
        }
        void ckChoice_CheckedChangedEx(object sender, DevComponents.DotNetBar.Controls.CheckBoxXChangeEventArgs e)
        {
            try
            {
                GridCheckBoxXEditControl ckChoice = sender as GridCheckBoxXEditControl;
                GrdCtNganh.PrimaryGrid.FlushActiveRow();
                //GhepNganhNghe();
            }
            catch (Exception ex)
            {
            }

            //ckChoice.EditorCell.RowIndex
        }
        void FrmE_HoSoMoi_RowChanged(object sender, DataRowChangeEventArgs e)
        {

        }
        void FrmE_HoSoMoi_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            try
            {
                if (e.Column.ColumnName == "Choice")
                {
                    GhepNganhNghe();
                    LoadGiayToTheoNganh(e.Row);
                    // bsNganhKD.ResetBindings(true);
                    object current = grdNganhDaChon.PrimaryGrid.DataSource;
                    grdNganhDaChon.PrimaryGrid.DetachDataSource(false);
                    grdNganhDaChon.SetDataSource(current);
                }
            }
            catch (Exception ex)
            {
                e.Row.RejectChanges();
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }
        void LoadGiayToTheoNganh(DataRow nganhRow)
        {


            int isChoide = Convert.ToInt32(nganhRow["Choice"]);
            DataTable tblTpHoSo = bsCtTpHoSo.DataSource as DataTable;
            DataRow[] giayToCuaNganh = tblCacheGiayToKemTheo.Select("Ma_DoiTuong='" + nganhRow["Ma_Nganh"].ToString() + "' AND Loai_DoiTuong=2");

            if (tblGiayToHienTai == null)
                tblGiayToHienTai = tblCacheGiayToKemTheo.Clone();

            if (isChoide == 1)
            {
                bool flagAddToGiayToHienTai = false;
                int count = tblGiayToHienTai.Select("Ma_DoiTuong='" + nganhRow["Ma_Nganh"].ToString() + "' AND Loai_DoiTuong=2").Length;
                if (count == 0)
                {
                    flagAddToGiayToHienTai = true;

                }
                foreach (DataRow row in giayToCuaNganh)
                {
                    if (flagAddToGiayToHienTai)
                        tblGiayToHienTai.ImportRow(row);
                    DataRow[] exists = tblTpHoSo.Select("Ma_LoaiGt='" + row["Ma_LoaiGt"].ToString() + "'");
                    if (exists.Length == 0)
                    {
                        AddGiayTo(tblTpHoSo, row);
                    }
                    else
                    {
                        if (exists[0].IsNull("Bat_Buoc"))
                            exists[0]["Bat_Buoc"] = false;
                        if ((bool)exists[0]["Bat_Buoc"])
                        {
                            exists[0]["Bat_Buoc"] = row["Bat_Buoc"];
                        }
                    }
                }
            }
            else
            {
                //Xóa danh sách giấy tờ trong giấy tờ hiện tại
                foreach (DataRow row in giayToCuaNganh)
                {
                    DataRow[] founds = tblGiayToHienTai.Select(string.Format(
                              "Ma_LoaiGt='{0}' AND Ma_DoiTuong='{1}' AND Loai_DoiTuong='{2}'",
                              row["Ma_LoaiGt"], row["Ma_DoiTuong"], row["Loai_DoiTuong"]
                              ));
                    if (founds.Length > 0)
                    {
                        founds[0].Delete();
                    }
                    //Xóa danh sách giấy tờ trong tpHoSo nếu có
                    founds = tblGiayToHienTai.Select("Ma_LoaiGt='" + row["Ma_LoaiGt"].ToString() + "'");
                    if (founds.Length == 0)
                    {
                        founds = tblTpHoSo.Select("Ma_LoaiGt='" + row["Ma_LoaiGt"].ToString() + "'");
                        if (founds.Length > 0)
                            founds[0].Delete();
                    }
                    else
                    {
                        if ((bool)row["Bat_Buoc"])
                        {
                            bool batBuoc = false;
                            foreach (DataRow row2 in founds)
                            {
                                if ((bool)row2["Bat_Buoc"])
                                {
                                    batBuoc = true;
                                    break;
                                }
                            }
                            if (!batBuoc)
                            {
                                founds = tblTpHoSo.Select("Ma_LoaiGt='" + row["Ma_LoaiGt"].ToString() + "'");
                                if (founds.Length > 0)
                                    founds[0]["Bat_Buoc"] = batBuoc;

                            }
                        }

                    }

                }

            }


        }
        private void AddGiayTo(DataTable tblTpHoSo, DataRow giayToKemTheo)
        {
            DataRow newRow = tblTpHoSo.NewRow();
            newRow["Stt_Rec"] = BL_KPCommon.EmptySttRec;
            newRow["Ma_LoaiGt"] = giayToKemTheo["Ma_LoaiGt"];
            newRow["Co"] = 0;
            newRow["Noi_Cap"] = "";
            newRow["Ghi_chu"] = "";
            newRow["Ma_TcGt"] = "";
            newRow["Bat_Buoc"] = giayToKemTheo["Bat_Buoc"];

            newRow["Ten_LoaiGt"] = giayToKemTheo["Ten_LoaiGt"];
            tblTpHoSo.Rows.Add(newRow);

        }
        private void GhepNganhNghe()
        {
            DataTable tblData = bsNganhKD.DataSource as DataTable;
            DataRow[] choicedNganhNghe = tblData.Select("Choice=1");
            string nganh = "";
            foreach (DataRow row in choicedNganhNghe)
            {
                if (nganh.Length > 0)
                    nganh += ",";
                nganh += row["Ten_Nganh"].ToString();

            }
            if (!string.IsNullOrEmpty(txtNganhNgheKhac.Text))
                nganh += nganh.Length > 0 ? "," : "" + txtNganhNgheKhac.Text;
            txtNoi_Dung.Text = nganh;
        }
        public void InitDatasource()
        {
            dsDKHoSoKD.Tables.Add(_CastBussines.GetSchema());
            BL_KPGiayToKemTheo blGiayToKemTheo = new BL_KPGiayToKemTheo();
            tblCacheGiayToKemTheo = blGiayToKemTheo.Select();


            ParentBinding = (CurrencyManager)BindingContext[
               dsDKHoSoKD.Tables[
               _CastBussines.DataTable]];
        }
        void LoadTpHoSoSchema()
        {
            if (dsDKHoSoKD.Tables.Contains("tblTPHoSo"))
                dsDKHoSoKD.Tables["tblTPHoSo"].Clear();
            else
            {
                dsDKHoSoKD.Merge(KP_BLListBase.GetSchema("tblTPHoSo"));
                dsDKHoSoKD.Tables["tblTPHoSo"].Columns.Add("Ten_LoaiGt");
                dsDKHoSoKD.Tables["tblTPHoSo"].Columns.Add("Bat_Buoc", typeof(bool));
            }
        }
        void LoadThanhVienSchema()
        {
            if (dsDKHoSoKD.Tables.Contains("tblThanhVienHSo"))
                dsDKHoSoKD.Tables["tblThanhVienHSo"].Clear();
            else
            {
                dsDKHoSoKD.Merge(KP_BLListBase.GetSchema("tblThanhVienHSo"));
            }
        }
        void LoadHoSoBySttRec(string sttRec)
        {
            dsDKHoSoKD.Tables[_CastBussines.DataTable].ImportRow(_CastBussines.SelectBySttRec(sttRec));
            // bindingSource.DataSource = dsDKHoSoKD.Tables[_CastBussines.DataTable];
            SetDataSource(ParentBinding.Current);

            LoadNganhHs(sttRec);
            LoadThanhVien(sttRec);

            dsDKHoSoKD.Merge(_CastBussines.SelectTPHoSoBySttRec(sttRec));
            bsCtTpHoSo.DataSource = dsDKHoSoKD.Tables["tblTPHoSo"];
        }
        void KiemTraGiayToKemTheoNganhNghe()
        {
            DataTable tblData= bsNganhKD.DataSource as DataTable;
            DataRow[] selecteds = tblData.Select("Choice=1");
            foreach (DataRow row in selecteds)
                LoadGiayToTheoNganh(row);
            
        }
        public void EditHoSo(string sttRec)
        {
            dsDKHoSoKD.Clear();
            if (!dsDKHoSoKD.Tables.Contains(_CastBussines.DataTable))
                InitDatasource();
            LoadDependencyData();
            LoadTpHoSoMacDinh(false);
            LoadHoSoBySttRec(sttRec);
            KiemTraGiayToKemTheoNganhNghe();
        }
        public void ViewMode(string sttRec)
        {
            dsDKHoSoKD.Clear();
            if (!dsDKHoSoKD.Tables.Contains(_CastBussines.DataTable))
                InitDatasource();
            LoadDependencyData();
            LoadTpHoSoMacDinh(false);
            LoadHoSoBySttRec(sttRec);
            KiemTraGiayToKemTheoNganhNghe();
            //
            grdNganhDaChon.PrimaryGrid.ReadOnly = true;
            GrdDsTV.PrimaryGrid.ReadOnly = true;
            GrdCtNganh.PrimaryGrid.ReadOnly = true;
            GrdCtNganh.PrimaryGrid.ReadOnly = true;

            FormState = FormState.Normal;
            kpucSaveItem.tsSaveItem.Items[0].Visible = false;
            kpucSaveItem.tsSaveItem.Items[1].Visible = false;

        }
        #region IRunCommand Members

        public void RunCommand(object sender, object commandData)
        {
            //throw new NotImplementedException();
        }

        #endregion

        #region Method
        string GetChuYNganh(DataRow rowNganh)
        {
            string chuy = "<b><font color=\"red\">Chú ý:</font></b>";
            if (!rowNganh.IsNull("Ghi_Chu"))
            {
                chuy += "<br/>&nbsp;&nbsp;&nbsp;" + rowNganh["Ghi_Chu"].ToString();

            }
            return chuy;
        }
        void AddGiayToKemTheo()
        {
            FrmE_AddGiayTo2HS frmAddTv = new FrmE_AddGiayTo2HS();
            try
            {
                frmAddTv.HoSoRec = CurrentRow["Stt_Rec"].ToString();
                frmAddTv.Business = Business;
                CurrencyManager cm = (CurrencyManager)BindingContext[bsCtTpHoSo];
                frmAddTv.AddNew(cm);
                frmAddTv.ShowDialog();
                GrdCtGiayto.PrimaryGrid.FlushActiveRow();
                GrdCtGiayto.PrimaryGrid.FlushSelected();
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Fatal("Thêm mới chứng từ kèm theo", ex);
                KPMessageBox.Show("Thêm mới chứng từ kèm theo\n" + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                frmAddTv.Business = null;
                //frmAddTv.Close();
                frmAddTv.Dispose();
            }
        }
        void AddThanhVien()
        {
            FrmE_ThanhVienEdit frmAddTv = new FrmE_ThanhVienEdit();
            try
            {
                frmAddTv.HoSoRec = CurrentRow["Stt_Rec"].ToString();

                frmAddTv.Business = Business;
                CurrencyManager cm = (CurrencyManager)BindingContext[bsThanhVien];
                frmAddTv.AddNew(cm);
                frmAddTv.ShowDialog();
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Fatal("Thêm mới thành viên", ex);
                KPMessageBox.Show("Thêm mới thành viên\n" + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                frmAddTv.Business = null;
                //frmAddTv.Close();
                frmAddTv.Dispose();
            }
        }
        /// <summary>
        /// Lấy đối tượng Grid đang hiển thị
        /// </summary>
        /// <returns></returns>
        SuperGridControl GetActiveGrid()
        {
            if (SupperTab1.SelectedTab == sTabItemNN)
                return GrdCtNganh;
            if (SupperTab1.SelectedTab == sTabItemGT)
                return GrdCtGiayto;
            if (SupperTab1.SelectedTab == sTabItemTV)
                return GrdDsTV;
            return null;

        }
        void EditThanhVien()
        {

            if (GrdDsTV.PrimaryGrid.ActiveRow == null)
                return;
            FrmE_ThanhVienEdit frmAddTv = new FrmE_ThanhVienEdit();
            try
            {
                frmAddTv.HoSoRec = CurrentRow["Stt_Rec"].ToString();

                frmAddTv.Business = Business;
                CurrencyManager cm = (CurrencyManager)BindingContext[bsThanhVien];
                frmAddTv.Edit(cm);
                frmAddTv.ShowDialog();
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Fatal("Thêm mới thành viên", ex);
                KPMessageBox.Show("Thêm mới thành viên\n" + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                frmAddTv.Business = null;
                //frmAddTv.Close();
                frmAddTv.Dispose();
            }
        }
        void EditGiayTo()
        {
            if (GrdCtGiayto.PrimaryGrid.ActiveRow == null)
                return;
            FrmE_AddGiayTo2HS frmAddTv = new FrmE_AddGiayTo2HS();
            try
            {
                frmAddTv.HoSoRec = CurrentRow["Stt_Rec"].ToString();
                frmAddTv.Business = Business;
                CurrencyManager cm = (CurrencyManager)BindingContext[bsCtTpHoSo];
                frmAddTv.Edit(cm);
                frmAddTv.ShowDialog();
                GrdCtGiayto.PrimaryGrid.FlushActiveRow();
                GrdCtGiayto.PrimaryGrid.FlushSelected();
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Fatal("Thêm mới chứng từ kèm theo", ex);
                KPMessageBox.Show("Thêm mới chứng từ kèm theo\n" + ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                frmAddTv.Business = null;
                //frmAddTv.Close();
                frmAddTv.Dispose();
            }
        }
        void DeleteThanhVien()
        {
            if (GrdDsTV.PrimaryGrid.ActiveRow != null)
            {
                DialogResult result = KPMessageBox.Show("Bạn muốn xóa thành viên góp vốn đang chọn?", KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.YesNo, KPMessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    GrdDsTV.PrimaryGrid.Rows.Remove(GrdDsTV.PrimaryGrid.ActiveRow);
                }
            }
        }
        void DeleteGiayTo()
        {
            if (GrdCtGiayto.PrimaryGrid.ActiveRow != null)
            {
                DialogResult result = KPMessageBox.Show("Bạn muốn xóa giấy tờ kèm theo đang chọn?", KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.YesNo, KPMessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    GrdCtGiayto.PrimaryGrid.Rows.Remove(GrdCtGiayto.PrimaryGrid.ActiveRow);
                }
            }
        }
        #endregion Method
        private void GrdMenuContext_PopupOpen(object sender, DevComponents.DotNetBar.PopupOpenEventArgs e)
        {
            // Debug.WriteLine("GrdMenuContext_PopupOpen");

            SuperGridControl grid = GetActiveGrid();
            if (grid.Equals(GrdDsTV))
                bbiChoiceList.Visible = false;
            else
                bbiChoiceList.Visible = true;

            DataRow currentRow = grid.GetCurrentRow();
            if (currentRow != null)
            {
                bbiDelete.Enabled = true;
                bbiEdit.Enabled = true;
                if (currentRow.RowState == DataRowState.Modified)
                    bbiRejectRow.Enabled = true;
                else
                    bbiRejectRow.Enabled = false;
            }
            else
            {
                bbiDelete.Enabled = false;
                bbiEdit.Enabled = false;

                bbiRejectRow.Enabled = false;
            }
        }
        private void bbiAddItem_Click(object sender, EventArgs e)
        {
            SuperGridControl grid = GetActiveGrid();
            if (grid == GrdDsTV)
            {
                AddThanhVien();
                return;
            }



            if (grid == GrdCtGiayto)
            {
                AddGiayToKemTheo();
                return;
            }
        }
        private void GrdCtNganh_SelectionChanged(object sender, GridEventArgs e)
        {
            try
            {
                DataRow row = GrdCtNganh.GetCurrentRow();
                // lbChuY.Text = GetChuYNganh(row);
            }
            catch (Exception ex)
            {

                LogUtil.Logger.Fatal("GrdCtNganh_SelectionChanged", ex);
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }

        }

        private void lbChuY_Click(object sender, EventArgs e)
        {
            MessageBox.Show(this.Size.ToString());
        }

        private void bbiEdit_Click(object sender, EventArgs e)
        {
            SuperGridControl grid = GetActiveGrid();
            if (grid == GrdDsTV)
            {
                EditThanhVien();
                return;
            }



            if (grid == GrdCtGiayto)
            {
                EditGiayTo();
                return;
            }
        }

        private void GrdCtGiayto_SelectionChanged(object sender, GridEventArgs e)
        {
            try
            {

                DataRow row = GrdCtGiayto.GetCurrentRow();
                bool flag = (bool)row["Bat_Buoc"];
                string chuy = string.Format("<b><font color=\"red\">Chú ý:{0}{1}</font></b>", row["Ten_LoaiGt"], (flag ? "(Bắt buộc)" : ""));
                string maloaigt = row["Ma_LoaiGt"].ToString();
                DataRow[] founds = tblGiayToHienTai.Select("Ma_LoaiGt='" + maloaigt + "'");
                flag = false;
                foreach (DataRow gtRow in founds)
                {
                    int loai = (int)gtRow["Loai_DoiTuong"];
                    if (!gtRow.IsNull("Ghi_Chu") && gtRow["Ghi_Chu"].ToString().Trim().Length > 0)
                    {
                        flag = true;
                        if (loai == 1)
                            chuy += string.Format("<br/><b>Loại hồ sơ:{0}</b>", gtRow["Ma_DoiTuong"]) + "<br/>" + gtRow["Ghi_Chu"].ToString();
                        else
                            chuy += string.Format("<br/><b>Mã ngành:{0}</b>", gtRow["Ma_DoiTuong"]) + "<br/>" + gtRow["Ghi_Chu"].ToString();
                    }
                    //chuy += "<br/>&nbsp;&nbsp;&nbsp;" + gtRow["Ghi_Chu"].ToString();
                }
                if (flag)
                    pNote.Text = chuy;
                else
                    pNote.Text = "";

                // lbChuY.Text = GetChuYNganh(row);
            }
            catch (Exception ex)
            {

                LogUtil.Logger.Fatal("GrdCtNganh_SelectionChanged", ex);
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
        }

        private void biThemTv_Click(object sender, EventArgs e)
        {
            bbiAddItem_Click(sender, e);
        }

        private void biSuaTv_Click(object sender, EventArgs e)
        {
            bbiEdit_Click(sender, e);
        }

        private void biXoaTv_Click(object sender, EventArgs e)
        {
            bbiDelete_Click(sender, e);
        }

        private void bbiDelete_Click(object sender, EventArgs e)
        {
            SuperGridControl grid = GetActiveGrid();
            if (grid == GrdDsTV)
            {
                DeleteThanhVien();
                return;
            }
            if (grid == GrdCtGiayto)
            {
                DeleteGiayTo();
                return;
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {

        }

        private void txtNganhNgheKhac_TextChanged(object sender, EventArgs e)
        {
            GhepNganhNghe();
        }

    }
}
